package com.travel.controller;

import com.travel.service.MinioService;
import com.travel.utils.CommonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.ClassUtils;
import org.springframework.util.ResourceUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.Date;

/**
 * @BelongsProject: TravelDream
 * @BelongsPackage: com.travel.controller
 * @CreateTime: 2021-05-18 14:52
 * @Description: TODO
 * 上传图片控制器
 */
@Controller
public class FileUploadController {
    @Autowired
    MinioService minioService;

    /**
     * 通用的文件上传
     * @param multipartFile
     * @param session
     * @return
     * @throws Exception
     */
    @RequestMapping("/uploadImgs/{address}")
    @ResponseBody
    public CommonResult upload(@PathVariable("address") String address,@RequestParam("file") MultipartFile multipartFile, HttpSession session) throws Exception{
        if (!StringUtils.isEmpty(multipartFile) && multipartFile.getSize()>0){

            String url = minioService.upload(multipartFile,address);
            if (!StringUtils.isEmpty(url)){
                return new CommonResult(200,"文件上传成功",url);
            } else {
                return new CommonResult(500,"文件上传失败");
            }
        }else {
            return new CommonResult(250,"上传文件为空");
        }
    }

    @RequestMapping("/uploadImg/{address}")
    @ResponseBody
    public CommonResult uploadM(@PathVariable("address") String address,
                                @RequestParam("file") MultipartFile[] multipartFiles, HttpSession session) throws Exception{
        String urls = "";
        for (MultipartFile multipartFile : multipartFiles) {
            if (!StringUtils.isEmpty(multipartFile) && multipartFile.getSize()>0){

                String url = minioService.upload(multipartFile,address);
                if (!StringUtils.isEmpty(url)){
                    urls += url+";";
                } else {
                    return new CommonResult(500,multipartFile.getOriginalFilename()+"文件上传失败");
                }
            }else {
                return new CommonResult(250,multipartFile.getOriginalFilename()+"上传文件为空");
            }
        }
        urls = StringUtils.trimTrailingCharacter(urls,';');
        if (StringUtils.isEmpty(urls)){
            return new CommonResult(500,"文件上传为空");
        } else {
            return new CommonResult(200,"文件上传成功",urls);
        }
    }

}
